//
//  SettingView.m
//  Honda
//
//  Created by Xiaolong Zhang on 13-4-23.
//  Copyright (c) 2013年 HeninHoo. All rights reserved.
//

#import "SettingView.h"
#import "CarsTableViewCell.h"
#import "ConfigCodeHelper.h"
#import "CarInfo.h"
#import "NetworkDefine.h"
#import "NetworkManager.h"
#import "LoginViewController.h"
#import "MainViewController.h"
#import "SHA1.h"
#import "LoginViewController.h"
@interface SettingView ()
@property (nonatomic, readonly) NetworkTask *logoutTask;
@property (nonatomic, readonly) NSString* ipConfig;
@end

@implementation SettingView
@synthesize closeCtrl           =   _closeCtrl;
@synthesize bgView              =   _bgView;
@synthesize carsTableView       =   _carsTableView;
@synthesize logoutCtrl          =   _logoutCtrl;
@synthesize carsDownloadCtrl    =   _carsDownloadCtrl;
@synthesize checkVersonCtrl     =   _checkVersonCtrl;
@synthesize settingIPCtrl       =   _settingIPCtrl;
@synthesize carsArr             =   _carsArr;
@synthesize logoutTask          =   _logoutTask;

@synthesize settingLine1        =   _settingLine1;
@synthesize settingLine2        =   _settingLine2;
@synthesize settingLine3        =   _settingLine3;
@synthesize downloadTopLine     =   _downloadTopLine;

@synthesize currentVersonLab    =   _currentVersonLab;
@synthesize copyrightLab        =   _copyrightLab;
@synthesize supportTelLab       =   _supportTelLab;

@synthesize ipConfig            =   _ipConfig;

@synthesize delegate            =   _delegate;

- (id)init
{
    self = [super init];
    if (self) {

    }
    return self;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    SafeRelease(_ipConfig);
    SafeRelease(_downloadTopLine);
    SafeRelease(_settingLine2);
    SafeRelease(_settingLine1);
    SafeRelease(_logoutTask);
    SafeRelease(_checkVersonCtrl);
    SafeRelease(_carsDownloadCtrl);
    SafeRelease(_logoutCtrl);
    SafeRelease(_carsTableView);
    SafeRelease(_bgView);
    SafeRelease(_closeCtrl);
    [super dealloc];
}

- (UIControl*)closeCtrl {
    if (nil == _closeCtrl) {
        _closeCtrl = [[UIControl alloc] init];
        _closeCtrl.backgroundColor = [UIColor clearColor];
        [_closeCtrl addTarget:self action:@selector(onTapCloseControl:) forControlEvents:UIControlEventTouchUpInside];
        
        [self addSubview:_closeCtrl];
    }
    
    return _closeCtrl;
}

- (UIImageView*)bgView {
    if (nil == _bgView) {
        _bgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"main_setting_bg"]];
        _bgView.userInteractionEnabled = YES;
        
        [self.closeCtrl addSubview:_bgView];
    }
    
    return _bgView;
}

- (UITableView*)carsTableView {
    if (nil == _carsTableView) {
        _carsTableView = [[UITableView alloc] init];
        _carsTableView.backgroundView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"main_download_bottom"]] autorelease];
        _carsTableView.delegate = self;
        _carsTableView.dataSource = self;
        _carsTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        [self.bgView addSubview:_carsTableView];
    }
    
    return _carsTableView;
}

- (SettingCustomControl*)logoutCtrl {
    if (nil == _logoutCtrl) {
        _logoutCtrl = [[SettingCustomControl alloc] init];
        _logoutCtrl.iconView.image = [UIImage imageNamed:@"main_quit"];
        _logoutCtrl.nameLab.text = @"注销登录";
        [_logoutCtrl addTarget:self action:@selector(onTapLogOutControl:) forControlEvents:UIControlEventTouchUpInside];
        
        [self.bgView addSubview:_logoutCtrl];
    }
    
    return _logoutCtrl;
}

- (SettingCustomControl*)carsDownloadCtrl {
    if (nil == _carsDownloadCtrl) {
        _carsDownloadCtrl = [[SettingCustomControl alloc] init];
        _carsDownloadCtrl.iconView.image = [UIImage imageNamed:@"main_download_button"];
        _carsDownloadCtrl.nameLab.text = @"资源下载";
        
        [self.bgView addSubview:_carsDownloadCtrl];
    }
    
    return _carsDownloadCtrl;
}

- (SettingCustomControl*)checkVersonCtrl {
    if (nil == _checkVersonCtrl) {
        _checkVersonCtrl = [[SettingCustomControl alloc] init];
        _checkVersonCtrl.iconView.image = [UIImage imageNamed:@"main_refres"];
        _checkVersonCtrl.nameLab.text = @"检查更新";
        [_checkVersonCtrl addTarget:self action:@selector(onTapCheckVersonControl:) forControlEvents:UIControlEventTouchUpInside];
        
        [self.bgView addSubview:_checkVersonCtrl];
    }
    
    return _checkVersonCtrl;
}

- (SettingCustomControl*)settingIPCtrl {
    if (nil == _settingIPCtrl) {
        _settingIPCtrl = [[SettingCustomControl alloc] init];
        _settingIPCtrl.iconView.image = [UIImage imageNamed:@"main_setting_ip"];
        _settingIPCtrl.nameLab.text = @"设置IP";
        [_settingIPCtrl addTarget:self action:@selector(onTapSettingIPControl:) forControlEvents:UIControlEventTouchUpInside];
        
        [self.bgView addSubview:_settingIPCtrl];
    }
    
    return _settingIPCtrl;
}

- (UIImageView*)settingLine1 {
    if (nil == _settingLine1) {
        _settingLine1 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"main_setting_line"]];
        [self.bgView addSubview:_settingLine1];
    }
    
    return _settingLine1;
}

- (UIImageView*)settingLine2 {
    if (nil == _settingLine2) {
        _settingLine2 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"main_setting_line"]];
        [self.bgView addSubview:_settingLine2];
    }
    
    return _settingLine2;
}

- (UIImageView*)settingLine3 {
    if (nil == _settingLine3) {
        _settingLine3 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"main_setting_line"]];
        [self.bgView addSubview:_settingLine3];
    }
    
    return _settingLine3;
}

- (UIImageView*)downloadTopLine {
    if (nil == _downloadTopLine) {
        _downloadTopLine = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"main_download_top"]];
        [self.bgView addSubview:_downloadTopLine];
    }
    
    return _downloadTopLine;
}

- (UILabel*)currentVersonLab {
    if (nil == _currentVersonLab) {
        _currentVersonLab = [[UILabel alloc] init];
        _currentVersonLab.backgroundColor = [UIColor clearColor];
        _currentVersonLab.textAlignment = NSTextAlignmentRight;
        _currentVersonLab.font = [UIFont systemFontOfSize:11];
        _currentVersonLab.textColor = [UIColor colorWithRed:99 / 255.0 green:99 / 255.0 blue:99 / 255.0 alpha:1.0];
        _currentVersonLab.text = [NSString stringWithFormat:@"当前版本V%@", [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"]];
        
        [self.checkVersonCtrl addSubview:_currentVersonLab];
    }
    
    return _currentVersonLab;
}

- (UILabel*)copyrightLab {
    if (nil == _copyrightLab) {
        _copyrightLab = [[UILabel alloc] init];
        _copyrightLab.backgroundColor = [UIColor clearColor];
        _copyrightLab.textAlignment = NSTextAlignmentRight;
        _copyrightLab.font = [UIFont systemFontOfSize:10];
        _copyrightLab.textColor = [UIColor colorWithRed:99 / 255.0 green:99 / 255.0 blue:99 / 255.0 alpha:1.0];
        _copyrightLab.text = @"广州汽车集团乘用车有限公司版权所有";
        
        [self.bgView addSubview:_copyrightLab];
    }
    
    return _copyrightLab;
}

- (UILabel*)supportTelLab {
    if (nil == _supportTelLab) {
        _supportTelLab = [[UILabel alloc] init];
        _supportTelLab.backgroundColor = [UIColor clearColor];
        _supportTelLab.textAlignment = NSTextAlignmentRight;
        _supportTelLab.font = [UIFont systemFontOfSize:10];
        _supportTelLab.textColor = [UIColor colorWithRed:99 / 255.0 green:99 / 255.0 blue:99 / 255.0 alpha:1.0];
        _supportTelLab.text = @"技术支持热线：";
        
        [self.bgView addSubview:_supportTelLab];
    }
    
    return _supportTelLab;
}

- (void)layoutSettingView {
    self.frame = CGRectMake(0, 0, 1024, 768);
    self.closeCtrl.frame = self.frame;
    
    self.bgView.frame = CGRectMake(680, 70, 350, 630);
    self.logoutCtrl.frame = CGRectMake(18, 19, 315, 70);
    self.settingLine1.frame = CGRectMake(18, 89, 315, 2);
    
//    self.carsDownloadCtrl.frame = CGRectMake(18, 89, 315, 70);
//    self.downloadTopLine.frame = CGRectMake(18, 159, 315, 10);
//    self.carsTableView.frame = CGRectMake(18, 159, 315, 260.5);
    
    self.settingIPCtrl.frame = CGRectMake(18, 92, 315, 70);
    
    self.settingLine2.frame = CGRectMake(18, 162, 315, 2);
    self.checkVersonCtrl.frame = CGRectMake(18, 165, 315, 70);
    self.currentVersonLab.frame = CGRectMake(220, 30, 85, 12);
    
    self.settingLine3.frame = CGRectMake(18, 235, 315, 2);
    self.copyrightLab.frame = CGRectMake(18, 245, 310, 11);
    self.supportTelLab.frame = CGRectMake(18, 256, 310, 11);
    
}

#pragma mark - 
- (void)onTapCloseControl:(UIControl*)closeControl {
    if ([self.delegate respondsToSelector:@selector(onTapCloseControlSettingView:)]) {
        [self.delegate onTapCloseControlSettingView:self];
    }
}

//点击“注销登录”
- (void)onTapLogOutControl:(UIControl*)logOutControl {
    NSLog(@"注销登录");
    
    UIAlertView* logoutAlert = [[UIAlertView alloc] initWithTitle:@"确定要注销登录？" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [logoutAlert show];
    SafeRelease(logoutAlert);
}

//点击“检查更新”
- (void)onTapCheckVersonControl:(UIControl*)checkVersonControl {
    NSLog(@"检查更新");
    
   // NSString* urlStr = [NSString stringWithFormat:@"%@GHAC_AppVersion.txt", PadDataURL];
    
    NetworkTask* checkVersonTask = [[NetworkTask alloc] initWithGetUrl:@"http://10.251.68.91/paddata/GHAC_AfterSale/GHAC_AppVersion.txt" getArgs:nil];
    //NSLog(@"%@",urlStr);
    checkVersonTask.indentifier = @"checkVerson";
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onSuccessSettingTask:) name:NetworkTask_NotificationName_OnSuccess object:checkVersonTask];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onFailSettingTask:) name:NetworkTask_NotificationName_OnFail object:checkVersonTask];
    
    [[NetworkManager getInstance] startTaskAsync:checkVersonTask];
    
    [[NetworkingViewController sharedController] showNetworkingWithTitle:@"检查中..." content:nil activiting:YES enableDismiss:NO];
}

- (void)onTapSettingIPControl:(UIControl*)settingIPControl {
    NSString* currentIP = [NSString stringWithFormat:@"%@", [[NSUserDefaults standardUserDefaults] objectForKey:@"ip"]];
    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"设置IP"
                                                    message:[NSString stringWithFormat:@"当前IP:%@",currentIP]
                                                   delegate:self
                                          cancelButtonTitle:@"取消"
                                          otherButtonTitles:@"完成", nil];
    
    alert.alertViewStyle = UIAlertViewStylePlainTextInput;
    
    UITextField* textField = [alert textFieldAtIndex:0];
    textField.delegate = self;
    textField.keyboardType = UIKeyboardTypeNumberPad;
    [alert show];
    SafeRelease(alert);
}

- (void)onSuccessSettingTask:(NSNotification*)notify {
    NetworkTask* task = notify.object;
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NetworkTask_NotificationName_OnSuccess object:task];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NetworkTask_NotificationName_OnFail object:task];
    
    NSLog(@"task.resultDict:%@", task.resultDict);
    
    if ([task.indentifier isEqualToString:@"SettingIP"]) {
        if (200 == task.statusCode) {
            [[NSUserDefaults standardUserDefaults] setObject:self.ipConfig forKey:@"ip"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            [NetworkManager getInstance].host = self.ipConfig;
            [[NetworkingViewController sharedController] showNetworkingWithTitle:@"设置成功!" content:nil activiting:NO enableDismiss:YES];
                        [[NetworkingViewController sharedController] showNetworkingWithTitle:@"正在注销" content:nil activiting:YES enableDismiss:YES];
            
            [self.delegate iszhuxiao:@"IS"];

          //  [[NetworkingViewController sharedController] performSelector:@selector(dismissNetworking) withObject:nil afterDelay:1.5];
        } else {
            [[NetworkingViewController sharedController] dismissNetworking];
            NSString* currentIP = [NSString stringWithFormat:@"%@", [[NSUserDefaults standardUserDefaults] objectForKey:@"ip"]];
            UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"设置IP"
                                                            message:[NSString stringWithFormat:@"设置失败，请重新设置，当前IP:%@",currentIP]
                                                           delegate:self
                                                  cancelButtonTitle:@"取消"
                                                  otherButtonTitles:@"完成", nil];
            alert.alertViewStyle = UIAlertViewStylePlainTextInput;
            UITextField* textField = [alert textFieldAtIndex:0];
            textField.delegate = self;
            textField.keyboardType = UIKeyboardTypeNumberPad;
            [alert show];
            SafeRelease(alert);
        }
        SafeRelease(_ipConfig);
        
    } else if ([task.indentifier isEqualToString:@"Logout"]) {
        if ([self.delegate respondsToSelector:@selector(onTapCloseControlSettingView:)]) {
            [self.delegate onTapCloseControlSettingView:self];
        }
        [ConfigCodeHelper shareInstance].customerInfo = nil;
       // [[MainViewController sharedViewController] login];
        
    } else if ([task.indentifier isEqualToString:@"checkVerson"]) {
        //修改
        NSString* updataVerson = [task.resultDict objectForKey:@"GHAC_AppVersion"];
        NSString* currentVerson = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
        
        if (updataVerson.floatValue > currentVerson.floatValue) {
            [[NetworkingViewController sharedController] dismissNetworking];
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:APPUpdateURL]];
        } else {
            [[NetworkingViewController sharedController] showNetworkingWithTitle:@"已经是最新版本！" content:nil activiting:NO enableDismiss:YES];
        }
    }
}

- (void)onFailSettingTask:(NSNotification*)notify {
    NetworkTask* task = notify.object;
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NetworkTask_NotificationName_OnSuccess object:task];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NetworkTask_NotificationName_OnFail object:task];
    NSLog(@"onFailSettingTask:%@", task.resultDict);
    
    if ([task.indentifier isEqualToString:@"SettingIP"]) {
        [[NetworkingViewController sharedController] dismissNetworking];
        NSString* currentIP = [NSString stringWithFormat:@"%@", [[NSUserDefaults standardUserDefaults] objectForKey:@"ip"]];
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"设置IP"
                                                        message:[NSString stringWithFormat:@"设置失败，请检查网络，当前IP:%@",currentIP]
                                                       delegate:self
                                              cancelButtonTitle:@"取消"
                                              otherButtonTitles:@"完成", nil];
        alert.alertViewStyle = UIAlertViewStylePlainTextInput;
        UITextField* textField = [alert textFieldAtIndex:0];
        textField.delegate = self;
        textField.keyboardType = UIKeyboardTypeNumberPad;
        [alert show];
        SafeRelease(alert);
        SafeRelease(_ipConfig);
    } else if ([task.indentifier isEqualToString:@"Logout"]) {
        
    } else if ([task.indentifier isEqualToString:@"checkVerson"]) {
        [[NetworkingViewController sharedController] showNetworkingWithTitle:@"检查更新失败，请检查网络！" content:nil activiting:YES enableDismiss:YES];
    }
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.carsArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CarInfo* car = [self.carsArr objectAtIndex:indexPath.row];
    
    CarsTableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:car.name];
    if (nil == cell) {
        cell = [[[CarsTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:car.name] autorelease];
        NSLog(@"%@",car.name);
        
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        
    }
    
    cell.carInfo = car;
    
    return cell;
}

#pragma mark - UITableViewDelegate
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 65;
}

#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if ([alertView.title isEqualToString:@"设置IP"]) {
        if (0 == buttonIndex) {
            return;
        }
        UITextField* textField = [alertView textFieldAtIndex:0];
        _ipConfig = [textField.text copy];
        NSString* url = [NSString stringWithFormat:@"http://%@/paddata/source.txt", _ipConfig];
        
        NetworkTask* task = [[NetworkTask alloc] initWithGetUrl:url getArgs:nil];
        task.indentifier = @"SettingIP";
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onSuccessSettingTask:) name:NetworkTask_NotificationName_OnSuccess object:task];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onFailSettingTask:) name:NetworkTask_NotificationName_OnFail object:task];
        [[NetworkManager getInstance] startTaskAsync:task];
        SafeRelease(task);
        [[NetworkingViewController sharedController] showNetworkingWithTitle:@"设置中..." content:nil activiting:YES enableDismiss:NO];
        
    } else if ([alertView.title isEqualToString:@"确定要注销登录？"]){
        if (1 == buttonIndex) {
            [self.delegate iszhuxiao:@"IS"];

        }
    }
}

- (BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView *)alertView {
    if ([alertView.title isEqualToString:@"设置IP"]) {
        UITextField* textField = [alertView textFieldAtIndex:0];
        if ([NSString invalidString:textField.text]) {
            return NO;
        }
    }
    
    return YES;
}

#pragma mark - UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    return ([string isEqualToString:[string stringByReplacingOccurrencesOfString:@"[^0-9.]*" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, string.length)]]
            ? YES
            : NO);
}
@end
